package org.example.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtil {
    // 数据源
    private static DataSource dataSource;
    private static final String DRUID_CONF_FILENAME = "druid.properties";
    // 静态代码块做初始化
    static {
        try {
            // 1. 加载配置文件
            InputStream inputStream = DruidUtil.class.getClassLoader().getResourceAsStream(DRUID_CONF_FILENAME);
            Properties properties = new Properties();
            properties.load(inputStream);
            // 2. 让Druid读取配置文件初始化数据源 (此时8个连接已经创建好了)
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 获取数据库连接 (此处会有多线程并发安全的问题)
    public static synchronized Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    // 关闭连接
    // Druid在底层进行了改动,调用close函数并没有真的断开连接,只是归还连接
    public static void closeConnection(Connection conn) {
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}